// 处方管理
const express = require('express')
const { query } = require('../db')
const router = express.Router()
// 处方列表
router.get('/',async (req,res,next) => {
  const page = 10
  // 获取get传递的参数
  const obj = req.query
  console.log(obj)
  // 判断页码
  if(!obj.pno) {
    obj.pno = 1
  }
  let start = (obj.pno - 1) * page
  // 执行SQL命令
  try {
    var data = await query(`select a.id,a.cate,a.result,a.doctor,a.user,a.status,a.ctime,a.stime,a.apothecary,a.rate,a.usage,a.content,b.num,b.status from hs_recipel a,hs_order b where a.order_id=b.id limit ${start},${page};select count(*) n from hs_recipel a,hs_order b where a.order_id=b.id`)
  } catch(err) {
    return next(err)
  }
  res.send({
    code: 200,
    msg: '处方列表',
    data: data[0],
    total: data[1][0].n,
    pno: obj.pno
  })
})
// 处方详情(get /detail)
router.get('/detail', async (req,res,next) => {
  // 获取处方的id
  const { id } = req.query
  if(!id) {
    res.send({
      code: 401,
      msg: '处方id不能为空'
    })
  }
  // 执行SQL命令，查询出处方下的药品
  try {
    var data = await query(`select b.title,b.pic,a.dose,a.usage from hs_recipel_medicine a,hs_medicine b where a.mid=b.id && rid=${id}`)
  } catch(err) {
    return next(err)
  }
  console.log(data)
  res.send({
    code: 200,
    msg: '处方详情',
    data
  })
})
// 审核(get /verify)
router.get('/verify', async (req,res,next) => {
  // 获取处方的id、审核状态的结果
  const { id,status } = req.query
  if(!id) {
    return res.send({
      code: 401,
      msg: '处方的id不能为空'
    })
  }
  if(!status) {
    return res.send({
      code: 402,
      msg: '处方审核状态不能为空'
    })
  }
  // 执行SQL命令
  try {
    var data = await query('update hs_recipel set status=? where id=?',[status,id])
  } catch(err) {
    return next(err)
  }
  console.log(data)
  if(data.changedRows === 0) {
    res.send({
      code: 410,
      msg: '审核失败'
    })
  } else {
    res.send({
      code: 200,
      msg: '审核成功'
    })
  }
})


module.exports = router